package com.zhiqianbao.mycoupon;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.activity.MyCouponActivity;
import com.zhiqianbao.adapter.CouponAdapter;
import com.zhiqianbao.entity.CouponInfo;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.view.PullToRefreshLayout;
import com.zhiqianbao.view.PullableListView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by hp on 2017/7/17.
 */
public class BeOverdueConponFragment extends Fragment {
    PullableListView listView;
    PullToRefreshLayout superRefreshLayout;
    ImageView defaultImg;
    TextView couponDataMsg;
    RelativeLayout noDataLayout;
    private CouponAdapter couponAdapter;
    private boolean isLoading = false;//判断是否是第一次加载数据
    private boolean isRefresh = false;//执行刷新操作
    private int totalPages = 0;//总页数
    private int pageNum = 1;//当前显示页数
    protected View mRoot;
    protected LayoutInflater mInflater;
    public String serviceType = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mRoot != null) {
            ViewGroup parent = (ViewGroup) mRoot.getParent();
            if (parent != null) {
                parent.removeView(mRoot);
            }
        } else {
            mRoot = inflater.inflate(R.layout.fragment_mycoupon_layout1, container, false);
            mInflater = inflater;
            initWidget(mRoot);
            initData();
        }
        return mRoot;
    }
    public void initWidget(View root){
        listView=(PullableListView)root.findViewById(R.id.listView);
        superRefreshLayout=(PullToRefreshLayout)root.findViewById(R.id.refresh_view);
        defaultImg=(ImageView)root.findViewById(R.id.default_img);
        couponDataMsg=(TextView)root.findViewById(R.id.coupon_data_msg);
        noDataLayout=(RelativeLayout)root.findViewById(R.id.no_data_layout);
        superRefreshLayout.setOnRefreshListener(new MyListener());
    }

    private class MyListener implements PullToRefreshLayout.OnRefreshListener {

        @Override
        public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
            onRefreshing();
        }

        @Override
        public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
            // 加载操作
            onLoadMoreData();
        }
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void initData() {
        serviceType = ((MyCouponActivity) getActivity()).serviceType;
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (serviceType.equals("2")) {
                    CouponInfo.DataBean.CouponListBean listBean = couponAdapter.getItem(position);
                    Intent intent = new Intent();
                    intent.putExtra("name", listBean.getName());
                    intent.putExtra("end_time", listBean.getEndTime());
                    intent.putExtra("note", listBean.getNote());
                    intent.putExtra("couponType", String.valueOf(listBean.getCouponType()));
                    intent.putExtra("couponId", String.valueOf(listBean.getId()));
                    getActivity().setResult(Activity.RESULT_OK, intent);
                    getActivity().finish();
                }
            }
        });
        onRefreshing();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void onRefreshing() {
        isRefresh = true;
        pageNum = 1;
        userCouponList(pageNum);
    }

    public void onLoadMoreData() {
        isRefresh=false;
        if (pageNum * 10 < totalPages) {
            pageNum++;
            userCouponList(pageNum);
        }
        else{
            superRefreshLayout.loadmoreFinish(PullToRefreshLayout.NODATE1);
        }
    }
    public static final int DATA_FILED=0x123;
    public static final int DATA_SCUESSFUL=0x124;
    private Gson gson = new Gson();
    /**
     * （userId:用户编号；type：1,2,3分别表示未使用,已使用,已过期；
     *  serviceType=1表示更多里优惠券列表;serviceType=2表示还款时可用优惠券列表）
     */
    private void userCouponList(final int pageNum){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                mapParams.put("type", "3");
                mapParams.put("serviceType",serviceType);
                mapParams.put("pageSize", "10");
                mapParams.put("pageNum", String.valueOf(pageNum));
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/activity/userCouponList",
                        mapParams, getActivity());
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FILED;
                } else {
                    message.what = DATA_SCUESSFUL;
                    CouponInfo data =gson.fromJson(result, CouponInfo.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FILED:
                    if (!isLoading) {
                        superRefreshLayout.setVisibility(View.GONE);
                        noDataLayout.setVisibility(View.VISIBLE);
                        couponDataMsg.setText("抱歉，加载数据失败！");
                    }
                    break;
                case DATA_SCUESSFUL:
                    CouponInfo response = (CouponInfo) msg.obj;
                    if (response != null) {
                        if (response.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            CouponInfo.DataBean dataBean = response.getData();
                            if (dataBean != null) {
                                totalPages = dataBean.getTotalCount();
                                List<CouponInfo.DataBean.CouponListBean> couponListBeanList
                                        = dataBean.getCouponList();
                                if (!isLoading) {
                                    isLoading = true;
                                    superRefreshLayout.setVisibility(View.VISIBLE);
                                    noDataLayout.setVisibility(View.GONE);
                                    if (dataBean.getIsUseCount() == 0) {
                                        superRefreshLayout.setVisibility(View.GONE);
                                        noDataLayout.setVisibility(View.VISIBLE);
                                        couponDataMsg.setText("暂无优惠券");
                                    } else {
                                        couponAdapter = new CouponAdapter(getActivity());
                                        couponAdapter.addAllData(couponListBeanList);
                                        listView.setAdapter(couponAdapter);
                                    }
                                } else {
                                    ((MyCouponActivity) getActivity()).refreshTabLayoutTitle(dataBean);
                                    if (isRefresh) {
                                        if (couponAdapter != null) {
                                            couponAdapter.clearData();
                                            if (couponListBeanList != null) {
                                                couponAdapter.addAllData(couponListBeanList);
                                                couponAdapter.notifyDataSetChanged();
                                            }
                                        }
                                        try {
                                            superRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                        } catch (NullPointerException exception) {
                                            Log.i("NullPointerException", exception.getMessage());
                                        }
                                    } else {
                                        if (couponAdapter != null) {
                                            if (couponListBeanList != null) {
                                                couponAdapter.addAllData(couponListBeanList);
                                                couponAdapter.notifyDataSetChanged();
                                            }
                                        }
                                        try {
                                            superRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                                        } catch (NullPointerException exception) {
                                            Log.i("NullPointerException", exception.getMessage());
                                        }
                                    }
                                }
                            }
                        } else {
                            if (!isLoading) {
                                isLoading = true;
                                superRefreshLayout.setVisibility(View.GONE);
                                noDataLayout.setVisibility(View.VISIBLE);
                                couponDataMsg.setText(response.getMsg());
                            }
                        }
                    } else {
                        if (!isLoading) {
                            superRefreshLayout.setVisibility(View.GONE);
                            noDataLayout.setVisibility(View.VISIBLE);
                            couponDataMsg.setText("抱歉，加载数据失败！");
                        }
                    }
                    break;
            }
        }
    };
}
